package com.maple.aspect;

import com.maple.annotation.MyType;
import com.maple.constant.AutoFillConstant;
import com.maple.enumeration.OperationType;
import com.maple.utils.ThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class AutoFillAspect {
    @Pointcut("execution(* com.maple.mapper.*.*(..))  && @annotation(com.maple.annotation.MyType))")
    public void point(){}



    @Before("point()")
    public void autoFill(JoinPoint joinPoint) {
        log.info("对象属性自动填充切面方法开始");
//        获得方法签名上的注解
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        Method method = signature.getMethod();
        MyType annotation = method.getAnnotation(MyType.class);

//        获得方法的第一个参数
        Object[] args = joinPoint.getArgs();
        if(args == null || args.length == 0){
            return;
        }
        Object arg = args[0];


//        获得当前的时间和操作人id
        LocalDateTime localDateTime = LocalDateTime.now();
        Long id = ThreadLocalUtils.getCurrentId();


//        进行注解判断
        if(annotation.value() == OperationType.INSERT){
//            对象属性封装
            try {
                Method method1 = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
                method1.invoke(arg, localDateTime);
                Method method2 = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
                method2.invoke(arg, id);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        try {
            Method method3 = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            method3.invoke(arg, localDateTime);
            Method method4 = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
            method4.invoke(arg, id);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }



}
